package cn.tedu.fruitshop.service.impl;

import cn.tedu.fruitshop.ex.ServiceException;
import cn.tedu.fruitshop.mapper.MenuMapper;
import cn.tedu.fruitshop.pojo.dto.MenuAddNewDTO;
import cn.tedu.fruitshop.pojo.entity.Menu;
import cn.tedu.fruitshop.pojo.vo.MenuListItemVO;
import cn.tedu.fruitshop.service.MenuService;
import cn.tedu.fruitshop.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.rowset.serial.SerialException;
import java.util.List;

/**
 * @author www
 * @create 2022-11-05 18:03
 */
@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Override
    public void add(MenuAddNewDTO menuAddNewDTO) {
        log.debug("开始执行添加菜单的操作，参数:{}",menuAddNewDTO);
        log.debug("查询是否存在这个菜单");
        int rows = menuMapper.countByTitle(menuAddNewDTO.getTitle());
        if (0 < rows){
            String message = "该菜单已经存在，添加失败";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        Menu menu = new Menu();
        BeanUtils.copyProperties(menuAddNewDTO,menu);
        log.debug("不存在，开始添加，{}",menu);
        rows = menuMapper.insert(menu);
        if (1 != rows){
            String message = "添加失败,服务器繁忙，请稍后再试";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteByTitle(String title) {
        log.debug("开始执行【根据title删除菜单】的操作，参数:{}",title);
        log.debug("查询是否存在这个菜单");
        int rows = menuMapper.countByTitle(title);
        if (0 == rows){
            String message = "该菜单不存在，删除失败";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("存在，开始删除，{}",title);
        rows = menuMapper.deleteByTitle(title);
        if (1 != rows){
            String message = "删除失败,服务器繁忙，请稍后再试";
            log.debug("{}",message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public List<MenuListItemVO> list() {
        log.debug("开始查询菜单列表：无参");
        List<MenuListItemVO> list = menuMapper.list();
        log.debug("查询列表成功!参数为:"+list);
        return list;
    }
}
